<?php

namespace app\admin\model;

use think\Model;
use think\Db;

class Gonghuo extends Model
{

    

    

    // 表名
    protected $name = 'gonghuo';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'gongtime_text',
        'good_json_text',
    ];
    
            public function getGoodJsonTextAttr($value, $data)
    {
        if($data){
            $destination_json_text = json_decode($data['good_json'],true);
            return $destination_json_text;
        }
    }
protected static function init()
    {
        self::beforeInsert(function ($row) {
            $good_json = $row->good_json;
            $good_array = json_decode($good_json,true);
            foreach ($good_array as $key => $value) {
                $if_exist = Db::name('dinggood')->where(['name'=>$value['name']])->find();
                if($if_exist){
                    // now_fahuo_num 发货数量
                    Db::name('dinggood')->where(['name'=>$value['name']])->setInc('yifahuo_num',$value['yifahuo']);//yifahuo_num已发货数量
                    Db::name('dinggood')->where(['name'=>$value['name']])->setInc('sum_gong_num',$value['now_fahuo_num']);//sum_gong_num 总供货数量
                }
            }
            
        });
    }
    
    public function getGongtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['gongtime']) ? $data['gongtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setGongtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
            public function admin()
    {
        return $this->belongsTo('admin', 'user_id')->bind('nickname');
    }

}
